package vip.xiaonuo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.BufferUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.hutool.socket.aio.AioServer;
import cn.hutool.socket.aio.AioSession;
import cn.hutool.socket.aio.SimpleIoAction;
import cn.hutool.socket.nio.NioServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * SpringBoot方式启动类
 *
 * @author yubaoshan
 * @date 2017/5/21 12:06
 */
@SpringBootApplication
public class SnowyApplication {

    private static final Log log = Log.get();

    public static void main(String[] args) {
        SpringApplication.run(SnowyApplication.class, args);
        log.info(">>> " + SnowyApplication.class.getSimpleName() + " is success!");

//        AioServer aioServer = new AioServer(5000);
//        aioServer.setIoAction(new SimpleIoAction() {
//
//            @Override
//            public void accept(AioSession session) {
//                StaticLog.debug("【客户端】：{} 连接。", session.getRemoteAddress());
//                session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ==="));
//            }
//
//            @Override
//            public void doAction(AioSession session, ByteBuffer data) {
//                Console.log(data);
//
//                if(!data.hasRemaining()) {
//                    StringBuilder response = StrUtil.builder()//
//                            .append("HTTP/1.1 200 OK\r\n")//
//                            .append("Date: ").append(DateUtil.formatHttpDate(DateUtil.date())).append("\r\n")//
//                            .append("Content-Type: text/html; charset=UTF-8\r\n")//
//                            .append("\r\n")
//                            .append("Hello Hutool socket");//
//                    session.writeAndClose(BufferUtil.createUtf8(response));
//                }else {
//                    session.read();
//                }
//            }
//        }).start(true);

//        NioServer server = new NioServer(5000);
//        server.setChannelHandler((sc)->{
//            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
//            try{
//                //从channel读数据到缓冲区
//                int readBytes = sc.read(readBuffer);
//                if (readBytes > 0) {
//                    //Flips this buffer.  The limit is set to the current position and then
//                    // the position is set to zero，就是表示要从起始位置开始读取数据
//                    readBuffer.flip();
//                    //eturns the number of elements between the current position and the  limit.
//                    // 要读取的字节长度
//                    byte[] bytes = new byte[readBuffer.remaining()];
//                    //将缓冲区的数据读到bytes数组
//                    readBuffer.get(bytes);
//                    String body = StrUtil.utf8Str(bytes);
//                    Console.log("[{}]: {}", sc.getRemoteAddress(), body);
//                    doWrite(sc, body);
//                } else if (readBytes < 0) {
//                    IoUtil.close(sc);
//                }
//            } catch (IOException e){
//                throw new IORuntimeException(e);
//            }
//        });
//        server.listen();


//        try {
//            ServerSocket serverSocket = new ServerSocket(5000);
//            System.out.println("启动服务器....");
//            Socket socket = serverSocket.accept();
//            System.out.println("客户端："+socket.getInetAddress().getHostAddress()+"已连接到服务器");
//            BufferedReader br = new BufferedReader((new InputStreamReader(socket.getInputStream())));
//            CountDownLatch countDownLatch = new CountDownLatch(1);
//            ThreadUtil.execute(()->{
//                try{
//                    String msg;
//                    while (true){
//                        msg= br.readLine();
//                        if(StrUtil.isNotEmpty(msg)){
//                            System.out.println("客户端:"+msg);
//                        }
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            });
//            ThreadUtil.execute(()->{
//                try{
//                    while (true){
//                        Scanner scanner = new Scanner(System.in);
//                        String msg =scanner.nextLine();
//                        if(StrUtil.isNotEmpty(msg)){
//                            if(msg=="exit"){
//                                countDownLatch.countDown();
//                            }else{
//                                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//                                bw.write(msg+"\n");
//                                bw.flush();
//                            }
//                        }
//                    }
//                }catch (Exception e){
//
//                }
//            });
//            countDownLatch.await();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static void doWrite(SocketChannel channel, String response) throws IOException {
        response = "收到消息：" + response;
        //将缓冲数据写入渠道，返回给客户端
        channel.write(BufferUtil.createUtf8(response));
    }

}
